package com.wj.algorithm.lintcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class P57 {
    private static int count = 0;

    public ArrayList<Integer> find(int[] arr, int fronIndex, int targetValue) {
        ArrayList<Integer> list = new ArrayList<>();

        int len = arr.length;
        for(int i = fronIndex + 1; i < len; i ++) {
            count ++;
            if(arr[i] == targetValue) {
                list.add(targetValue);
            }
        }
        
        return list;
    }
    
    
    public ArrayList<ArrayList<Integer>> findTwo(int[] arr, int fronIndex, int targetValue) {
        ArrayList<ArrayList<Integer>> list = new ArrayList<>();

        int len = arr.length;
        for(int i = fronIndex + 1; i < len; i ++) {
            int v = arr[i];
            int subTarget = targetValue - v;

            count ++;
            ArrayList<Integer> subs = find(arr, i, subTarget);
            for(Integer sub : subs) {
                ArrayList<Integer> tempList = new ArrayList<>();
                tempList.add(v);
                tempList.add(sub);
                list.add(tempList);
            }
        }
        
        return list;
    }

    public ArrayList<ArrayList<Integer>> threeSum(int[] numbers) {
        ArrayList<ArrayList<Integer>> list = new ArrayList<>();
        Arrays.sort(numbers);
        
        int len = numbers.length;
        for(int i = 0; i < len; i ++) {
            int v = numbers[i];
            int target = 0 - v;
            ArrayList<ArrayList<Integer>> tempList = findTwo(numbers, i, target);
            count ++;
            for(ArrayList<Integer> tempSub : tempList) {
                tempSub.add(v);
                Collections.sort(tempSub);
                if(!list.contains(tempSub)) {
                    list.add(tempSub);
                }
            }
        }
        
        return list;
    }
    
    public static void main(String[] args) {
        System.out.println(new P57().threeSum(new int[]{-1, 0, 1, 2, -1, -4}));
        System.out.println(count);
    }
}
